﻿using BCComponent;
using BCDto.Common.SystemExceptionRecord;
using BCService.Common.ExceptionService;
using Newtonsoft.Json.Linq;
using Pomelo.AspNetCore.TimedJob;
using System;

namespace BCTMSRESTful.Configs
{
    public class AutoExecutionJob : Job
    {
        private readonly ISystemExceptionRecordService exceptionRecordService;
        private readonly ITaskProcess taskProcess;

        public AutoExecutionJob(ISystemExceptionRecordService exceptionRecordService, ITaskProcess taskProcess)
        {
            this.exceptionRecordService = exceptionRecordService;
            this.taskProcess = taskProcess;
        }

        [Invoke(Begin = "2017-11-15 00:00", Interval = 1000 * 3600 * 1, SkipWhileExecuting = true)]
        public void Run()
        {
            try
            {
                taskProcess.RunJobs();
            }
            catch (Exception ex)
            {
                SystemExceptionRecordDto exceptionDto = new SystemExceptionRecordDto
                {
                    Name = ex.GetType().Name,
                    HelpLink = ex.HelpLink,
                    Message = ex.Message,
                    StackTrace = ex.StackTrace,
                    HResult = ex.HResult,
                    Data = JObject.FromObject(ex.Data).ToString(),
                    CreateTime = DateTime.Now
                };
                this.exceptionRecordService.Create(exceptionDto);
            }
        }
    }
}
